`

We assign the output of the nmap command to the variable

NMAP_RESULTS 1. In this command, we also filter for specific

lines containing the words Nmap scan report or tcp open.

These lines are part of Nmaps standard port scan output and they

indicate that open ports were found on an IP address.

We use a while loop to read NMAP_RESULT line by line,

checking whether each line contains the string report for 2. This

line will hold the IP address where ports were found open. If such a

line exists, we assign it to the ip variable. Then we parse the line to

extract the port that was found open 3. At 4, we create the file

variable to hold the file we’ll create on disk with the naming scheme

port-NUMBER.txt. Lastly, we append the IP address to the file 5.

You can download the script at https://github.com/dolevf/Black-

Hat-Bash/blob/master/ch04/nmap_to_portfiles.sh. Save it to a file

named nmap_to_portfiles.sh and run it. Next, run ls -l to see what

files were created, and use cat to view their contents:

$ ls -l

total 24

-rw-r--r-- 1 kali kali 3448 Mar 6 22:18 172-16-10-hosts.txt

-rw-r--r-- 1 kali kali 13 Mar 8 22:34 port-21.txt

-rw-r--r-- 1 kali kali 25 Mar 8 22:34 port-22.txt

--snip--

$ cat port-21.txt

172.16.10.11

As you’ve seen, Nmaps standard output format is a little

challenging to parse, but not impossible. Its useful to know that

Nmap provides additional output format options we can use to parse

it more easily, especially for scripting purposes. One of these options

is the -oG flag, or the greppable output format. This option is grep

and awk friendly, as you can see in Listing 4-12.

$ nmap -iL 172-16-10-hosts.txt --open -oG -

Host: 172.16.10.1 () Status: Up

Host: 172.16.10.1 () Ports: 22/open/tcp//ssh/// Ignored State: closed (999)

Host: 172.16.10.10 () Status: Up

Host: 172.16.10.10 () Ports: 8081/open/tcp//blackice-icecap/// Ignored

State: closed (999)

--snip--

Listing 4-12

Nmap's greppable output

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks